package edu.neumont.MillerK.Tests;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import edu.neumont.MillerK.POJOs.Security;
import edu.neumont.MillerK.Web.DBQueries.DBQueries;
import edu.neumont.MillerK.Web.Entities.*;

/**
 * Servlet implementation class TesterServlet
 */
@WebServlet("/TesterServlet")
public class TesterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * This Servlet's entire existence is to provide
	 * a UserTransaction and an EntityManagerFactory
	 * both of which must be annotated in a servlet.
	 * 
	 * For testing purposes.
	 */
		
	@Resource
	UserTransaction utx;
	
	@PersistenceUnit
	EntityManagerFactory emf;
	
	private DBQueries dbQueries;
	private Security security;
	
	public TesterServlet(EntityManagerFactory emf, UserTransaction utx) {		
		dbQueries = new DBQueries(emf, utx);
		security = new Security();
	}
	
	public List<User> getUsers(){
		return dbQueries.getAllUsers();
	}
	
	public User createUser(String emailUsername, String password){
		String salt = security.generateSalt(password.length());
		User user = null;
		try {
			user = new User(emailUsername, security.SHAHash(password + salt), salt);
			dbQueries.createUser(user);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return user;
	}
	
	public User getUser(String emailUsername){
		return dbQueries.getUser(emailUsername);
	}
}
